package org.gongliang.service.sys;

import java.util.List;

import org.gongliang.common.base.CRUDService;
import org.gongliang.dao.sys.RoleDao;
import org.gongliang.entity.sys.Resources;
import org.gongliang.entity.sys.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* 
* @author 龚亮
* @version 1.0
* @date 2017年05月04日 01:40:25
*/
@Service
public class RoleService extends CRUDService<RoleDao, Role> {

	@Autowired
	private RoleDao roleDao;

	/**
	 * 
	 * @Description 查询用户所拥有的角色
	 * @author 龚亮
	 * @param userId
	 *            用户id
	 * @return 角色集合
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<Role> getUserRole(Long userId) {
		return roleDao.getUserRole(userId);
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public boolean saveUserRole(Long userId, List<Long> roleIds) {
		int i = 0;
		if (roleIds == null || roleIds.size() == 0) {
			i = roleDao.deleteUserRole(userId);
		} else {
			i = roleDao.deleteUserRole(userId);
			for (long roleId : roleIds) {
				i += roleDao.saveUserRole(userId, roleId);
			}
		}
		return retBool(i);
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public boolean deleteUserRole(Long userId) {
		return retBool(roleDao.deleteUserRole(userId));
	}

	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<Resources> getRoleResource(Long roleId) {
		return roleDao.getRoleResource(roleId);
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public boolean saveRoleResources(Long roleId, List<Long> resourceIds) {
		int i = 0;
		if (resourceIds == null || resourceIds.size() == 0) {
			i = roleDao.deleteRoleResources(roleId);
		} else {
			i = roleDao.deleteRoleResources(roleId);
			for (long resourceId : resourceIds) {
				i += roleDao.saveRoleResources(roleId, resourceId);
			}
		}
		return retBool(i);
	}
}
